import React from 'react';
import { connect } from 'react-redux';
import { Button, Row, Col, Card } from 'antd';
import NameListList from './list';
import CommonListsIndex from '../../../../components/CommonLists/index';
import FilterTool from '../../../../components/FilterTool';
import NameListAdd from './add';
import services from '../../../../services/api';
import { message } from 'antd';
import Modal from '../../../../components/Modal/index';
import EditComponent from '../add';
import SetValidTime from './setValidTime';
import { APIUrl } from '../../../../services/createServices';
import { AUDIT } from '../../../../utils/constant';

function mapStateToProps(state) {
  return {
    namelist_type: state.code.namelist_type,
    namelist_data_type: state.code.namelist_data_type,
    depts: state.global.depts,
  };
}

@connect(mapStateToProps)
class NameListIndex extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'nameListDetail';
    this.addComponent = NameListAdd;
    this.editComponent = NameListAdd;
    this.listsComponent = NameListList;
    this.model_width = '350px';
    this.queryParams = {};
    this.queryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.queryTableParams = {};
    this.state = {
      types: [
        {
          value: '1',
          name: '系统内置',
        },
        {
          value: '2',
          name: '自定义',
        },
      ],
      list: [],
      totalCount: 0,
      detail: {},
      name_list_id: props.onlyExport ? props.id : (props.isAuditLog ? props.record.name_list_id : props.match.params.id),
      name_list_data_ids: [],
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    this.props.dispatch({ type: 'pageClose/waringAdd' });
  }

  componentWillUnmount() {
    this.props.dispatch({ type: 'pageClose/waringReduce' });
  }

  queryList(params) {
    if (this.state.name_list_id) {
      params.name_list_id = this.state.name_list_id;
      services[this.api].list(params).then((res) => {
        if (res.code === 0) {
          const { list, totalCount } = res.data
          const currentPage = params.current_page
          const page = Math.ceil(totalCount / this.queryPanigation.page_size)
          if (list && totalCount && list.length === 0 && currentPage > page) {
            this.onChangePagination(page, 'current_page')
          } else {
            this.state.selectedRowKeys.splice(0);
            this.setState({
              ...res.data,
              name_list_data_ids: [],
              selectedRowKeys: [],
            });
          }
          // this.state.selectedRowKeys.splice(0);
          // this.setState({
          //   ...res.data,
          //   name_list_data_ids: [],
          //   selectedRowKeys: [],
          // });
        } else {
          message.error(res.msg);
        }
      });
    }
  }

  // 改变名单数据状态
  statusChange = (param, record) => {
    this.updateStatus(record.name_list_data_id, param ? 1 : 2);
  };

  updateStatus = (name_list_data_ids, status) => {
    services[this.api].updateStatus({ name_list_data_ids, status }).then((data) => {
      if (data.code === 0) {
        message.success(data.msg);
        this.freshQueryList();
      } else {
        message.error(data.msg);
      }
    });
  };

  // 批量启用
  enable = () => {
    if (this.state.name_list_data_ids.length < 1) {
      message.warning('请至少勾选一条名单数据');
      return;
    }
    this.updateStatus(this.state.name_list_data_ids.join(), 1);
  };
  // 批量停用
  disable = () => {
    if (this.state.name_list_data_ids.length < 1) {
      message.warning('请至少勾选一条名单数据');
      return;
    }
    this.updateStatus(this.state.name_list_data_ids.join(), 2);
  };
  // 批量删除
  deleteData = () => {
    if (this.state.name_list_data_ids.length < 1) {
      message.warning('请至少勾选一条名单数据');
      return;
    }
    Modal.open({
      title: '',
      isConfirm: true,
      width: '300px',
      content: '确定要删除?',
      isOkBtn: true,
      isCancelBtn: true,
      ok: () => {
        services[this.api]
          .updateStatus({ name_list_data_ids: this.state.name_list_data_ids.join(), status: '-2' })
          .then((data) => {
            if (data.code === 0) {
              message.success(data.msg);
              this.state.selectedRowKeys.splice(0);
              this.setState({
                name_list_data_ids: [],
                selectedRowKeys: [],
              });
              this.freshQueryList();
              Modal.close();
            } else {
              message.error(data.msg);
            }
          });
      },
      cancel: () => {
        Modal.close();
      },
    });
  };
  // 批量设置有效期
  setDatetime = () => {
    if (this.state.name_list_data_ids.length < 1) {
      message.warning('请至少勾选一条名单数据');
      return;
    }

    // 打开批量设置有效期的弹窗
    Modal.open({
      title: '设置有效期',
      width: '340px',
      content: <SetValidTime name_list_data_ids={this.state.name_list_data_ids} closeModal={this.closeModal} />,
      isOkBtn: false,
      maskClosable: false,
      isCancelBtn: false,
    });
  };

  // 批量导出数据
  exportData = (type) => {
    if (!type && this.state.name_list_data_ids.length < 1) {
      message.warning('请至少勾选一条名单数据');
      return;
    }
    const url = type ? APIUrl + '/namelist/export-all?name_list_id=' + this.state.name_list_id : APIUrl + '/namelist/export?name_list_data_ids=' + this.state.name_list_data_ids.join();
    const a = document.createElement('a');
    a.download = '名单数据';
    a.href = url;
    a.click();
  };

  render() {
    const ListsComponent = this.listsComponent;
    const data = [
      {
        type: 'Search',
        key: 'keyword',
        name: 'keyword',
        defaultValue: '',
        placeholder: '请输入名单数据名称',
      },
    ];
    // 名单数据选择配置
    const rowSelection = {
      columnWidth: 30,
      onChange: (selectedRowKeys, selectedRows) => {
        let name_list_data_ids = [];
        selectedRows.forEach((item) => {
          name_list_data_ids.push(item.name_list_data_id);
        });
        this.setState({
          name_list_data_ids,
          selectedRowKeys,
        });
      },
      getCheckboxProps: (record) => ({
        disabled: record.audit_status === AUDIT._WAIT,
      }),
      hideDefaultSelections: true,
      selectedRowKeys: this.state.selectedRowKeys,
    };

    return (
      <div style={{ marginBottom: '30px' }}>
        {!this.props.onlyExport && (
          <Card style={{ marginBottom: '20px' }}>
            <EditComponent
              ref='editForm'
              record={this.state.detail}
              actionType='update'
              id={this.state.name_list_id}
              {...this.props}
              freshQueryList={this.freshQueryList}
            />
          </Card>
        )}
        <Row type='flex' justify='space-between' align='middle'>
          {!this.props.onlyExport ? (
            <Col span={12}>
              <Button className='marr10' type='primary' onClick={this.enable}>
                启用
              </Button>
              <Button className='marr10' onClick={this.disable}>
                停用
              </Button>
              <Button className='marr10' onClick={this.deleteData}>
                删除
              </Button>
              <Button className='marr10' onClick={this.setDatetime}>
                设置有效期
              </Button>
            </Col>
          ) : (
            <Col span={12}>
              <Button type='primary' onClick={this.exportData.bind(this, false)}>
                导出数据
              </Button>
              <Button type='primary' style={{ marginLeft: 20 }} onClick={this.exportData.bind(this, true)}>
                导出全部
              </Button>
            </Col>
          )}
          <Col span={12}>
            <FilterTool
              data={data}
              colNum={1}
              query={this.freshQueryList}
              refreshFilter={this.refreshFilter}
              isOnChange={true}
              refresh={this.resetList}
            />
          </Col>
        </Row>
        <div className='inner-content' style={{ marginTop: '20px' }}>
          <ListsComponent
            ref='list'
            {...this.state}
            edit={this.edit}
            onlyExport={this.props.onlyExport}
            rowKey='name_list_data_id'
            queryList={this.freshQueryList}
            refreshTableFilter={this.refreshTableFilter}
            onChangePagination={this.onChangePagination}
            showDetail={this.showDetail}
            queryTableParams={this.queryTableParams}
            rowSelection={rowSelection}
            statusChange={this.statusChange}
            getFilterTitle={this.getFilterTitle}
          />
        </div>
      </div>
    );
  }
}

export default NameListIndex;
